<template>
    <div>
        <el-dialog v-model="props.showList" title="数据" @close="publicListCancel" width="55%">
            <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
                <el-form :model="searchFrom" ref="publicQueryForm" :inline="true">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model.trim="searchFrom.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </searchBox>
            <el-table :data="dataList" @selection-change="handleSelectionChange" v-if="props.newType === 'category'"
                ref="categoryRef" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="ID" prop="id" width="80" />
                <el-table-column prop="name" label="站点分类名称" />
                <el-table-column prop="productCategoryName" label="分类名称" />
            </el-table>

            <el-table :data="dataList" highlight-current-row @selection-change="handleSelectionChange"
                v-if="props.newType === 'product'" ref="productRef">
                <el-table-column type="selection" width="50" />
                <el-table-column property="id" label="ID" align="center" width="50" />
                <el-table-column label="商品信息" width="400">
                    <template #default="scope">
                        <div style="display: flex; gap: 20px;align-items: center;">
                            <div style="width: 50px;">
                                <image-preview :src="scope.row.newImage" :width="50" :height="50" />
                            </div>
                            <el-text line-clamp="3">{{ scope.row.name }}</el-text>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="品牌信息">
                    <template #default="scope">
                        <div style="display: flex; gap: 20px;align-items: center;">
                            <div style="width: 50px;">
                                <image-preview :src="scope.row.brand?.host" :width="50" :height="50" />
                            </div>
                            <el-text line-clamp="3">{{ scope.row.brand?.commonName }}</el-text>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column property="categoryName" label="商品类型" />
                <el-table-column property="price" label="价格" align="center">
                    <template #header>
                        价格（{{ priceUnit }}）
                    </template>
                </el-table-column>
                <el-table-column property="newStatus" label="状态" align="center" />
            </el-table>


            <el-table :data="dataList" @selection-change="handleSelectionChange" v-if="props.newType === 'news_detail'"
                ref="newsListRef">
                <el-table-column type="selection" width="50" />
                <el-table-column label="ID" prop="id" width="80" />

                <el-table-column label="封面图" width="100">
                    <template #default="scope">
                        <image-preview :src="scope.row.host" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="name" />
                <el-table-column label="文章信息">
                    <template #default="scope">
                        <el-space spacer=" " wrap>
                            <el-button>{{ scope.row.labelContent }}</el-button>
                            <el-button>{{ scope.row.countryName }}</el-button>
                            <el-button>{{ scope.row.languageName }}</el-button>
                            <el-button>{{ scope.row.siteArticleCategoryName }}</el-button>
                        </el-space>

                    </template>
                </el-table-column>
                <el-table-column label="时间" align="center">
                    <template #default="scope">
                        <el-text>{{ DateTime(scope.row.created) }}</el-text>
                    </template>
                </el-table-column>
            </el-table>
            <el-table :data="dataList" @selection-change="handleSelectionChange" v-if="props.newType === 'brand'"
                ref="brandListRef">
                <el-table-column type="selection" width="50" />
                <el-table-column label="ID" prop="id" width="80" />
                <el-table-column label="封面图" width="100">
                    <template #default="scope">
                        <image-preview :src="scope.row.newImage" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="name" />
            </el-table>
            <Pagination :total="publicTotal" :limit="publicListFrom.pageSize" :page="publicListFrom.pageNum"
                @pagination="handlePageChange"></Pagination>
            <template #footer>
                <el-button type="primary" @click="publicListSure"> 确定 </el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from "vue";
const emits = defineEmits(["publicListCancel", "publicListSure"]);
const { proxy } = getCurrentInstance();
const props = defineProps({
    showList: {
        type: Boolean,
        default: false,
    },
    // 传值数据对象
    from: {
        type: Object,
        default: {},
    },
    newType: {//标签类型
        type: String,
        default: "",
    },
    websiteId: {
        type: String,
        default: "",
    },
    languageId: {
        type: String,
        default: "",
    }
});
const publicListFrom = ref({
    pageNum: 1,
    pageSize: 10,
})
const searchFrom = ref({
    name: ''
})
const siteProductSortList = ref([])//商品分类列表数据
const siteProductList = ref([])//商品列表数据
const articlesList = ref([])//文章列表数据
const brandList = ref([])//品牌列表数据
const priceUnit = ref({})//基础信息货币数据



const siteProductSortListTotal = ref(0)//商品分类列表数据
const siteProductListTotal = ref(0)//商品列表数据
const articlesListTotal = ref(0)//文章列表数据
const brandListTotal = ref(0)//品牌列表数据

const dataList = ref([])
const publicTotal = ref(0)
const selectedRow = ref(null); // 记录当前选中的行
onMounted(() => {
    getProductClassification()//商品分类
    getProduct()//商品
    getArticlesList()//文章列表
    getBrandList()//品牌
    getBasics()// 获取基础信息
})
watch(
    () => props.showList,
    () => {
        if (!props.showList) return;
        getProcessing()
    })
const publicListSure = () => {
    // console.log(selectedRow.value);
    if (!selectedRow.value) return proxy.$modal.msgError("请勾选ID");
    emits("publicListSure", selectedRow.value)
}
const publicListCancel = () => {
    selectedRow.value = null
    let selectedRowRef;
    if (props.newType === "category") {//商品分类====分类名称-c-分类id，树形结构
        selectedRowRef = proxy.$refs["categoryRef"]
        selectedRowRef.clearSelection(); // 清除所有选中
    } else if (props.newType === "product") {//商品=== 商品名称-p-商品id
        selectedRowRef = proxy.$refs["productRef"]
        selectedRowRef.clearSelection(); // 清除所有选中
    } else if (props.newType === "news_detail") {//文章详情===博客名称-n-博客id
        selectedRowRef = proxy.$refs["newsListRef"]
        selectedRowRef.clearSelection(); // 清除所有选中

    } else if (props.newType === "brand") {//品牌详情:  品牌名称-b-品牌id
        selectedRowRef = proxy.$refs["brandListRef"]
        selectedRowRef.clearSelection(); // 清除所有选中
    }
    emits("publicListCancel")
}
const getProductClassification = (name) => {
    site.general
        .sitecategoryList({
            data: {
                ...publicListFrom.value,
                param: {
                    websiteId: Number(props.websiteId),
                    languageId: Number(props.languageId),
                    fatherId: 0,
                    name: name || ''
                }
            }
        })
        .then((res) => {//商品分类
            siteProductSortListTotal.value = res.total
            siteProductSortList.value = res.data;
            // console.log(  siteProductSortList.value , '商品分类');
        });
}
const getProduct = (name) => {//商品列表
    site.general
        .sitewebsiteproductList({
            data: {
                ...publicListFrom.value,
                param: {
                    websiteId: Number(props.websiteId),
                    name: name || ''
                }
            },
        })
        .then((res) => {//商品
            siteProductListTotal.value = res.total
            if (res.data?.length) {
                res.data = res.data.map(code => {
                    return {
                        ...code,
                        newStatus: code.status === 1 ? '已上架' : code.status === 2 ? '已永久下架' : code.status === 0 ? '已临时下架' : '',
                        newImage: handleImage(code)
                    }
                })
            }

            siteProductList.value = res.data
            // console.log(siteProductList.value, '商品');
        });
}

const getArticlesList = (name) => {//文章列表
    site.general
        .sitearticleList({
            data: {
                ...publicListFrom.value,
                param: {
                    websiteId: Number(props.websiteId),
                    title: name || ''
                }
            },
        })
        .then((res) => {//文章
            if (res.data?.length) {
                res.data = res.data.map(code => {
                    return {
                        ...code,
                        name: code.title
                    }
                })
            }
            articlesListTotal.value = res.total
            articlesList.value = res.data
        })

}
const getBrandList = (name) => {
    site.general
        .sitewebsitebrandList({
            data: {
                ...publicListFrom.value,
                param: {
                    websiteId: Number(props.websiteId),
                    name: name || ''
                }
            },
        })
        .then((res) => {//商品品牌
            brandListTotal.value = res.total
            if (res.data?.length) {
                res.data = res.data.map(code => {
                    return {
                        ...code,
                        name: code.commonName,
                        newImage: handleImage(code)
                    }
                })
            }
            brandList.value = res.data;
            // console.log(brandList.value, '商品品牌');
        });
}
const handleQuery = () => {

}
const resetQuery = () => {

}
const handlePageChange = (newPage) => {
    publicListFrom.value.pageNum = newPage.page;
    publicListFrom.value.pageSize = newPage.limit;
    if (props.newType === "category") {//商品分类====分类名称-c-分类id，树形结构
        getProductClassification()
    } else if (props.newType === "product") {//商品=== 商品名称-p-商品id
        getProduct()
    } else if (props.newType === "news_detail") {//文章详情===博客名称-n-博客id
        getArticlesList()
    } else if (props.newType === "brand") {//品牌详情:  品牌名称-b-品牌id
        getBrandList()
    }
    getProcessing()
};



const getProcessing = () => {
    let selectedRowRef;
    if (props.newType === "category") {//商品分类====分类名称-c-分类id，树形结构
        dataList.value = siteProductSortList.value
        publicTotal.value = siteProductSortListTotal.value
        setTimeout(() => {
            selectedRowRef = proxy.$refs["categoryRef"]
            getWebsiteIds(selectedRowRef)
        }, 500);
    } else if (props.newType === "product") {//商品=== 商品名称-p-商品id
        dataList.value = siteProductList.value
        publicTotal.value = siteProductListTotal.value
        setTimeout(() => {
            selectedRowRef = proxy.$refs["productRef"]
            getWebsiteIds(selectedRowRef)
        }, 500);
    } else if (props.newType === "news_detail") {//文章详情===博客名称-n-博客id
        dataList.value = articlesList.value
        publicTotal.value = articlesListTotal.value
        setTimeout(() => {
            selectedRowRef = proxy.$refs["news_detail"]
            getWebsiteIds(selectedRowRef)
        }, 500);

    } else if (props.newType === "brand") {//品牌详情:  品牌名称-b-品牌id
        dataList.value = brandList.value
        publicTotal.value = brandListTotal.value
        setTimeout(() => {
            selectedRowRef = proxy.$refs["brandListRef"]
            getWebsiteIds(selectedRowRef)
        }, 500);
    }
}
const getWebsiteIds = (selectedRowRef) => {
    console.log(selectedRowRef, props.from);
    if (props.from?.id) {
        const existingRow = dataList.value.find((item) => item.id === props.from?.id);
        if (existingRow) {
            selectedRowRef.toggleRowSelection(existingRow, true);
        }
    }
};
const getBasics = () => {
    site.general
        .sitewebsiteGetbyid({
            pathParams: {
                id: Number(props.websiteId),
            },
        })
        .then((res) => {
            priceUnit.value = res.data.currency.description;

        })
}
const handleImage = (row) => {
    var imageExtensionsRegex = /^https?:\/\//i;
    // console.log(imageExtensionsRegex.test(row.mainImage));
    if (!imageExtensionsRegex.test(row.mainImage)) {
        return row.host
    } else {
        return row.mainImage
    }
}
const handleSelectionChange = (selection) => {
    let selectedRowRef;
    if (props.newType === "category") {//商品分类====分类名称-c-分类id，树形结构
        selectedRowRef = proxy.$refs["categoryRef"]
    } else if (props.newType === "product") {//商品=== 商品名称-p-商品id
        selectedRowRef = proxy.$refs["productRef"]

    } else if (props.newType === "news_detail") {//文章详情===博客名称-n-博客id
        selectedRowRef = proxy.$refs["newsListRef"]

    } else if (props.newType === "brand") {//品牌详情:  品牌名称-b-品牌id
        selectedRowRef = proxy.$refs["brandListRef"]
    }

    if (selection.length > 1) {
        // 保持单选，取消之前的选择
        const lastSelected = selection[selection.length - 1]; // 取最后选中的
        selectedRowRef.clearSelection(); // 清除所有选中
        selectedRowRef.toggleRowSelection(lastSelected, true); // 只保留最新选中的
        selectedRow.value = lastSelected;
    } else {
        selectedRow.value = selection[0] || null;
    }
    // console.log(selectedRow.value);
}



</script>
<style lang="scss" scoped>
/* 自定义勾选框样式 */
:deep(.el-checkbox__inner) {
    border-radius: 50%;
    /* 将边框半径设置为 50% 以创建圆形 */
    //   background-color: #409EFF; /* 可选：设置背景颜色 */
}

/* 未选中时的勾选框样式 */
:deep(.el-checkbox__inner) {
    border-radius: 50%;
    /* 将边框半径设置为 50% 以创建圆形 */
}
</style>